import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'navigation_bar_item.dart';

/// 封装底部导航栏方法
/// NavigationBarItem组件-在navigation_bar_item.dart 文件
class NavigationBarWidget extends StatefulWidget {
  NavigationBarWidget(
      {super.key,
      required this.pages,
      required this.labels,
      required this.icons,
      required this.activeIcons,
      this.onTabChange,
      this.currentIndex,
      this.onTabReload
      }) {
    if (pages.length != labels.length &&
        pages.length != icons.length &&
        pages.length != activeIcons.length) {
      throw Exception("数组长度必须保持一致");
    }
  }

  // 页面数组
  final List<Widget> pages;

  // 底部标题
  final List<String> labels;

  // 导航栏的icon数组：切换前
  final List<Widget> icons;

  // 导航栏的icon数组：切换后
  final List<Widget> activeIcons;

  // 自定义封装组件实例
  final ValueChanged<int>? onTabChange;

  // 页面重新加载
  final ValueChanged<int>? onTabReload;

  int? currentIndex;

  @override
  State<StatefulWidget> createState() {
    return _NavigationBarWidgetState();
  }
}

class _NavigationBarWidgetState extends State<NavigationBarWidget> {
  // int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: IndexedStack(
            index: widget.currentIndex ?? 0,
            children: widget.pages,
          ),
        ),
        bottomNavigationBar: Theme(
          // 去除切换时效果
          data: Theme.of(context).copyWith(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent),
          child: BottomNavigationBar(
            // 文字选中颜色
            type: BottomNavigationBarType.fixed,
            selectedLabelStyle: TextStyle(fontSize: 14, color: Colors.black),
            unselectedLabelStyle:
                TextStyle(fontSize: 12, color: Colors.blueGrey),
            currentIndex: widget.currentIndex ?? 0,
            items: _barItemList(),
            onTap: (index) {
              widget.currentIndex = index;
              // 自定义封装组件
              widget.onTabChange?.call(index);
              // 调用重新加载方法
              widget.onTabReload?.call(index);
              // 更新页面
              setState(() {});
            },
          ),
        ));
  }

  List<BottomNavigationBarItem> _barItemList() {
    List<BottomNavigationBarItem> items = [];

    // 便利传值
    for (int i = 0; i < widget.pages.length; i++) {
      items.add(BottomNavigationBarItem(
          label: widget.labels[i],
          activeIcon: NavigationBarItem(builder: (context) {
            return widget.activeIcons[i];
          }),
          icon: widget.icons[i]));
    }

    return items;
  }
}
